#include "boundingBox.h"
#include <limits>
#include "mesh.h"
#include <d3dx9.h>

using namespace ns;

BoundingBox::BoundingBox(Mesh* mesh){
	minX = minY = minZ = std::numeric_limits<float>::max();
	maxX = maxY = maxZ = std::numeric_limits<float>::lowest();
		
	for(int i = 0; i<mesh->GetVertexAmmount();i++){		
		if(minX >  mesh->GetVertices()[i].x){
			minX = mesh->GetVertices()[i].x;
		}
		if(minY > mesh->GetVertices()[i].y){
			minY = mesh->GetVertices()[i].y;
		}
		if(minZ > mesh->GetVertices()[i].z){
			minZ = mesh->GetVertices()[i].z;
		}

		if(maxX <  mesh->GetVertices()[i].x){
			maxX = mesh->GetVertices()[i].x;
		}
		if(maxY < mesh->GetVertices()[i].y){
			maxY = mesh->GetVertices()[i].y;
		}
		if(maxZ < mesh->GetVertices()[i].z){
			maxZ = mesh->GetVertices()[i].z;
		}
	}

	boundingVertices = new ColorVertex[8];
	
	boundingVertices[0].x = minX;
	boundingVertices[0].y = minY;
	boundingVertices[0].z = minZ;
								
	boundingVertices[1].x = minX;
	boundingVertices[1].y = maxY;
	boundingVertices[1].z = minZ;
								
	boundingVertices[2].x = maxX;
	boundingVertices[2].y = maxY;
	boundingVertices[2].z = minZ;
								
	boundingVertices[3].x = maxX;
	boundingVertices[3].y = minY;
	boundingVertices[3].z = minZ;
								
	boundingVertices[4].x = maxX;
	boundingVertices[4].y = minY;
	boundingVertices[4].z = maxZ;
								
	boundingVertices[5].x = maxX;
	boundingVertices[5].y = maxY;
	boundingVertices[5].z = maxZ;
								
	boundingVertices[6].x = minX;
	boundingVertices[6].y = maxY;
	boundingVertices[6].z = maxZ;
	
	boundingVertices[7].x = minX;
	boundingVertices[7].y = minY;
	boundingVertices[7].z = maxZ;
	
	boundingVertices[0].color = 0xff0000;
	boundingVertices[1].color = 0xff0000;
	boundingVertices[2].color = 0xff0000;
	boundingVertices[3].color = 0xff0000;
	boundingVertices[4].color = 0xff0000;
	boundingVertices[5].color = 0xff0000;
	boundingVertices[6].color = 0xff0000;
	boundingVertices[7].color = 0xff0000;
}

ColorVertex* BoundingBox::GetVertices(){
	return boundingVertices;
}

void BoundingBox::UpdateBB(D3DXMATRIX m){
	for(int i =0;i<8;i++) {
		D3DXVECTOR3 vector;
		vector.x=boundingVertices[i].x;
		vector.y=boundingVertices[i].y;
		vector.z=boundingVertices[i].z;
		D3DXVECTOR4 vec;
		D3DXVec3Transform(&vec,&vector,&m);
		boundingVertices[i].x = vec.x;
		boundingVertices[i].y = vec.y;
		boundingVertices[i].z = vec.z;
	}
}